import re

from django.http import JsonResponse
from django.views import View

from tools import get_user_dict
from tools.response_code import get_resp_dict
from tools.token import make_token
from user.models import User


class UsersView(View):
    """
    UsersView视图：处理user_user表的各种操作
    访问路由：/user/users
    """

    def post(self, request):
        """
        用户注册并登录
        """
        # 用户名获取和有效性验证
        username = request.POST.get('username')
        if not username:
            result = get_resp_dict(code=10100)
            return JsonResponse(result)
        try:
            User.objects.get(username=username)
            result = get_resp_dict(code=10101)
            return JsonResponse(result)
        except Exception as e:
            print(e)

        # 邮箱获取和有效性验证
        email = request.POST.get('email')
        if email:
            pattern = r'^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$'
            if not re.match(pattern, email):
                result = get_resp_dict(code=10102)
                return JsonResponse(result)

        # 密码获取和有效性验证
        password_1 = request.POST.get('password_1')
        if not password_1:
            result = get_resp_dict(code=10103)
            return JsonResponse(result)
        password_2 = request.POST.get('password_2')
        if password_1 != password_2:
            result = get_resp_dict(code=10104)
            return JsonResponse(result)

        try:
            user = User.objects.create_user(username=username,
                                            password=password_1,
                                            email=email)
        except Exception as e:
            print(e)
            result = get_resp_dict(code=99999, msg='注册失败，请重试')
            return JsonResponse(result)

        # 注册成功，颁发token
        token = make_token(user.id).decode()
        user_dict = get_user_dict(user)
        result = get_resp_dict({'token': token, 'user': user_dict})
        return JsonResponse(result)


class UserView(View):
    """
    UserView视图：处理user_user表单条记录的各种操作
    访问路由：/user/users/<int:id>
    """
    pass


class TokensView(View):
    """
    TokensView视图：处理登录和token的颁发
    访问路由：/user/tokens
    """

    def post(self, request):
        """
        用户登录
        """
        # 用户名获取和有效性验证
        username = request.POST.get('username')
        if not username:
            result = get_resp_dict(code=10200)
            return JsonResponse(result)
        try:
            user = User.objects.get(username=username)
        except Exception as e:
            print(e)
            result = get_resp_dict(code=10202)
            return JsonResponse(result)

        # 密码获取和有效性验证
        password = request.POST.get('password')
        if not password:
            result = get_resp_dict(code=10201)
            return JsonResponse(result)
        if not user.check_password(password):
            result = get_resp_dict(code=10202)
            return JsonResponse(result)

        # 登录成功，颁发token
        token = make_token(user.id).decode()
        user_dict = get_user_dict(user)
        result = get_resp_dict({'token': token, 'user': user_dict})
        return JsonResponse(result)


def avail_name_view(request):
    """
    检查某个用户名是否可以注册
    200: 可以注册
    404： 不可注册
    访问路由：/user/avail_name
    """
    username = request.GET.get('username')
    try:
        User.objects.get(username=username)
        return JsonResponse(get_resp_dict(code=404))
    except:
        return JsonResponse(get_resp_dict())
